﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace StarUtils.Extension
{
    public static class JsonHelper
    {
        public static string JsonDateTimeFormat(string json)
        {
            json = Regex.Replace(json, "\\\\/Date\\((\\d+)\\)\\\\/", (Match match) => new DateTime(1970, 1, 1).AddMilliseconds(long.Parse(match.Groups[1].Value)).ToString("yyyy-MM-dd HH:mm:ss.fff"));
            return json;
        }

        public static T ToObject<T>(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return default(T);
            }

            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch
            {
                return default(T);
            }
        }

        public static object ToObject(string json, Type type)
        {
            return JsonConvert.DeserializeObject(json, type);
        }

        public static string ToJson(object target, bool isConvertToSingleQuotes = false, bool camelCase = false, bool indented = false)
        {
            if (target == null)
            {
                return "{}";
            }

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            if (camelCase)
            {
                jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            if (indented)
            {
                jsonSerializerSettings.Formatting = Formatting.Indented;
            }

            string text = JsonConvert.SerializeObject(target, jsonSerializerSettings);
            if (isConvertToSingleQuotes)
            {
                text = text.Replace("\"", "'");
            }

            return text;
        }

        public static void SerializableToFile(string fileName, object obj)
        {
            lock (obj)
            {
                using FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);
                using StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8);
                streamWriter.Write(ToJson(obj, isConvertToSingleQuotes: false, camelCase: false, indented: true));
            }
        }

        public static T DeserializeFromFile<T>(string fileName)
        {
            try
            {
                using FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);
                using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
                return ToObject<T>(streamReader.ReadToEnd());
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static string ToJsonByForm(string formStr)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            string[] array = formStr.Split('&');
            for (int i = 0; i < array.Length; i++)
            {
                string[] array2 = array[i].Split('=');
                StringBuilder stringBuilder = new StringBuilder(array2[1]);
                for (int j = 2; j <= array2.Length - 1; j++)
                {
                    stringBuilder.Append(array2[j]);
                }

                dictionary.Add(array2[0], stringBuilder.ToString());
            }

            return dictionary.ToJson();
        }
    }
}
